<template>
  <div class="apply" ref="scrollOne">
    <!-- <header-com :title="getlist.name" moduleName="match" v-if="window.sessionStorage.getItem('club_id')!=''"></header-com> -->
		<div class="header">
			<a :href="formalUrl"><i class="iconfont icon-zuo" style="flex: 0.2"></i></a>
			<span>{{getlist.name}}</span>
			<img :src="getlist.logo" alt="" v-if="getlist.logo">
		</div>
		<div class="position"></div>
    <div class="matchInfo">
     <!-- <div class="matchName">
        <span class="applyName">{{ getlist.name }}</span>
        <img :src="getlist.logo" class="logo" />
      </div> -->
      <div class="matchInfo">
        <div>主办单位：{{ getlist.host }}</div>
        <div v-for="(item) in getlist.com_unit" :key="item.id">
          {{item.title}}：
          <span>{{item.content}}</span>
          <!-- 赛事运营支持：
          <span v-for="(item, index) in getlist.assist" :key="`${index}a`">
            {{ item }}
            <span v-if="index != (getlist.assist.length-1)">,</span>
          </span> -->
        </div>
        <div>赛事联络人：{{ getlist.major }}</div>
        <div>报名开始时间：{{ getlist.apply_start_time }}</div>
        <div>报名截止时间：{{ getlist.end_time }}</div>
        <div>比赛开始时间：{{ getlist.start_time }}</div>
        <div>比赛地点：{{ getlist.address }}</div>
				<div @click="goUsers" class="hasSign">>>>点击查看报名成功列表<<<</div>
      </div>
      <div class="teamBtnParen">
        <!-- <div class="teamBtn">项目组别</div> -->
        <a class="tips" target="_blank" :href="rules.com_info.rule">查看竞赛规程</a>
        <div class="judgmentApply" v-if="judgmentBtn" @click="judgmentApply">申请执裁</div>
      </div>
      <div class="teamList">
        <div class="teamItem" v-for="(item, index) in getlist.com_project" :key="`${index}b`">
          <div class="teamItem-top">{{ item.group }}{{ item.type }}</div>
          <div class="teamItem-middle"  v-if="item.age != null && item.age != ''">
            <div>年龄限制：{{ item.age.split(',')[0] + '至' + item.age.split(',')[1] }}</div>
            <!-- <div v-if="item.age == null || item.age == ''">年龄限制：无限制</div> -->
          </div>
          <div class="teamItem-middle" v-if="item.limit != 0">
            <!-- <div v-if="item.limit == 0">人数限制：无限制</div> -->
            <div>人数限制：{{ item.count }}/{{ item.limit }}</div>
          </div>
          <div class="teamItem-bot">
            <div>价格：{{ item.price }}元</div>
            <div class="signBtn" @click="apply(item.id, item.type, item.group)" v-if="applyEndTime == 2&&item.count!=undefined && item.limit > 0  && item.count<item.limit">报名</div>
            <div class="signBtn" @click="apply(item.id, item.type, item.group)" v-else-if="applyEndTime == 2 && item.count==undefined&&item.limit==0">报名</div>
            <div class="signBtn" v-else-if="applyEndTime == 2 &&item.count == item.limit">人数已报满</div>
            <div class="signBtn" v-if="applyEndTime == 1" @click="showMsg">报名未开始</div>
            <div class="signBtn" v-if="applyEndTime == 3">报名已结束</div>
          </div>
        </div>
      </div>
    </div>
		<!-- <div class="title" >
			<span class="matchName">{{rules.com_info.name}}</span><img :src="rules.com_info.logo" alt="">
		</div> -->
		<!-- <a class="tips" target="_blank" :href="rules.com_info.rule">查看竞赛规程</a> -->
		<div style="position: relative;min-height: 5vh;">	
			<div class="article" v-html="rules.content" ></div>	
			<div id="sign-btn" @click="Apply()" v-show="showbtn">立即报名</div>
		</div>
		<!-- <div class="sign-btn" @click="Apply()">前往报名</div> -->
		<!-- <div class="sign-btn" @click="checkRules()">查看竞赛规程</div> -->
	</div>
</template>
<script>
import {HOST} from "../../../main.js"
import { Dialog } from 'vant';
import { mapGetters, mapState } from 'vuex';
import { Toast } from 'vant';
import sdk from '../../../wxsdk/sdk.js'; //引入sdk.js
export default {
  name: 'index',
  data() {
    return {
      getlist: [],
			rules:[],
      sign_up: '',
      check: null,
      sign_type:1,
			formalUrl:'',
			// testUrl:'',
      judgmentBtn: false,
      id: this.$route.query.id,
			showbtn:false,
			test:false//测试服true 正式服 false
    };
  },
	created() {
    // console.log(HOST);
		// http://tennis.laigl.com/mobile/?code=031CN0Ga1JCUjA0k3gHa1bIhOZ1CN0G6&state=1#/
		// let herf = window.location.href
			this.formalUrl = HOST+'mobile/#/match?club_id='+window.sessionStorage.getItem('club_id')
		setTimeout(()=>{
			console.log(this.getlist)
		},500)
	},
  mounted() {
    this.com_list();
    this.checkedUserInfo();
		this.getRules()
		window.addEventListener('scroll', this.getScroll);
		let _this = this;
		window.onscroll = function(){
			//变量scrollTop是滚动条滚动时，距离顶部的距离
			var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
			//变量windowHeight是可视区的高度
			var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
			//变量scrollHeight是滚动条的总高度
			var scrollHeight = document.documentElement.scrollHeight||document.body.scrollHeight;
			//滚动条到底部的条件
			if(scrollTop+windowHeight == scrollHeight){
			//到了这个就可以进行业务逻辑加载后台数据了
				_this.showbtn = true
			}else{
				_this.showbtn = false;
			} 
		}
  },
	destroyed(){
		window.removeEventListener('scroll', this.getScroll);
	},
  computed: {
    ...mapGetters(['GET_SEX']),
    ...mapState(['age']),
    applyEndTime() {
      let current = Date.parse(new Date()) / 1000;
      let end = Date.parse(new Date(this.getlist.end_time.replace(/-/g, '/'))) / 1000;
      let start = Date.parse(new Date(this.getlist.apply_start_time.replace(/-/g, '/'))) / 1000; //开始报名时间
      if (current >= start && current < end) {
        return 2;
      } else if (current < start) {
        return 1;
      } else if (current > end) {
        return 3;
      }
    }
  },
  methods: {
		//监听滚动
		getScroll(){
				let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
				let clientHeight = document.documentElement.clientHeight;
				let scrollHeight = document.documentElement.scrollHeight;
				if (scrollTop + clientHeight >= scrollHeight) {
					console.log("滚动到底部了")
					this.showbtn = true
				}else{
					this.showbtn = false
				}
		},
		// 查看已报名人信息
		goUsers(){
			this.$router.push({
			  path: '/match/HasSign',
				query:{
					com_id:this.$route.query.id
				}
			});
    },
    // 报名未开始展示弹窗
    showMsg(){
      Toast({
        message: `报名开始时间：${this.getlist.apply_start_time}`
      })
    },
		// 前往报名
		Apply(){
			// var gotop = setInterval(()=>{
				document.body.scrollTop = 0
				document.documentElement.scrollTop = 0
			// },100)
			// this.$once('hook:beforeDestroy', () => {            
			//     clearInterval(gotop);                                    
			// })
		},
		getRules(){
			let com_id = this.$route.query.id
			this.$axios.post('/mobile/matching/get_rule',{com_id})
			.then(res=>{
				this.rules = res.data.data
			})
			.catch(res=>{
				console.log(res)
			})
		},
    wxShare() {
      let url = window.location.href.split('#')[0];
      let logo = this.getlist.logo;
      let name = this.getlist.name;
      let time = this.getlist.start_time
      let obj = {
        title: name, //分享标题

        desc: [this.getlist.share_time, this.getlist.address].join('\r\n'), //分享内容
        // desc: '快来报名吧~', //分享内容
        linkurl: location.protocol + '//' + location.host + '/mobile/#' + window.location.href.split('#')[1], //分享链接
        img: logo //分享内容显示的图片
      };
      sdk.getJSSDK(url, obj); //传入sdk.js需要的参数
    },
		// 查看竞赛规程
		checkRules(){
			let id = this.$route.query.id
			this.$router.push({
			  path: '/match/MatchRules',
			  query: {
			    id
			  }
			});
		},
    apply(project_id, projectType, group) {
      if(this.sign_type==1){
        Toast('本次比赛只接受指定单位报名！');
        return
      }
      let age = this.ages(this.age);
      if (this.check) {
        this.$axios
          .get('/mobile/v1/apply/sign_up_info', {
            params: {
              project_id: project_id
            },
            headers: {
              token: window.sessionStorage.getItem('token')
            }
          })
          .then(res => {
            if (res.data.code == 200) {
              if (res.data.data.sign_info.length != 0) {
                Toast('已报名');
                this.$router.push({
                  path: '/mine/newMatch'
                });
              } else {
                this.$router.push({
                  path: '/match/applyForm',
                  query: {
                    project_id: project_id,
                    projectType: projectType,
                    com_id: this.$route.query.id,
                    groups: group
                  }
                });
              }
            } else {
              Toast('请求失败请稍后再试！');
            }
          })
          .catch(res => {
            //  console.log(res.msg);
          });
      } else {
        this.$router.push({
          path: '/mine/setInfo'
        });
        Toast('请完善个人信息！');
      }
    },
    checkedUserInfo() {
      this.$axios
        .get('/mobile/v1/PersonalCenter/my_info', {
          headers: {
            token: window.sessionStorage.getItem('token')
          }
        })
        .then(res => {
          if (res.data.code == 2000) {
            this.$store.dispatch('SET_SEX', res.data.data.user_info.sex);
            if (res.data.data.user_info.type == 1 || res.data.data.user_info.type == 3) {
              this.judgmentBtn = true;
            }
            if (!res.data.data.user_info.id_card) {
              this.check = false;
              sessionStorage.setItem('isCompletedInfo', JSON.stringify(this.id)) //判断是否从个人信息回来
            } else {
              this.check = true;
            }
          }
        })
        .catch(res => {
          //console.log(res.msg);
        });
    },
    ages(str) {
      var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
      if (r == null) return false;
      var d = new Date(r[1], r[3] - 1, r[4]);
      if (d.getFullYear() == r[1] && d.getMonth() + 1 == r[3] && d.getDate() == r[4]) {
        var Y = new Date().getFullYear();
        return Y - r[1];
      }
      return '请完善个人信息！';
    },
    com_list(status) {
      this.$axios
        .get('/mobile/v1/apply/com_project', {
          params: {
            com_id: this.$route.query.id
          },
          headers: {
            token: window.sessionStorage.getItem('token')
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.sign_type = res.data.data.sign_type
            this.getlist = res.data.data;
            this.wxShare()
          }
        })
        .catch(res => {
          //  console.log(res.msg);
        });
    },
    judgmentApply() {
      Dialog.confirm({
        title: '申请执裁',
        message: '是否申请执裁？'
      })
        .then(() => {
          var params = new URLSearchParams();
          params.append('com_id', this.$route.query.id);
          this.$axios
            .post('/mobile/v1/apply/apply_ref', params, {
              headers: {
                token: window.sessionStorage.getItem('token')
              }
            })
            .then(res => {
              if (res.data.code == 2000) {
                Toast(res.data.msg);
              } else {
                Toast(res.data.msg);
              }
            })
            .catch(res => {
              //  console.log(res.msg);
            });
        })
        .catch(() => {
          Toast('您取消了申请执裁');
        });
    }
  }
};
</script>
<style lang="less" scoped>
.applyName {
  width: 80%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  text-align: left;
}
@keyframes scale{
	0%{
		transform: scale(1);
	}
	50%{
		transform: scale(1.02);
	}
	100%{
		transform: scale(1);
	} 
}
.hasSign{
	font-size: 17px;
	color: #42b574;
	font-weight: 700;
	// animation: scale 1s infinite linear;
}
.article{
	width: 90%;
	margin: 3% 5% 6% 5%;
	text-align: left;
	margin-bottom: 12vh;
	/deep/ img,video{
		max-width: 99%!important;
		// padding-left: 2%;
		// border: 1px solid red!important;
	}
	/deep/ h1,strong{
		border-left: 10px solid red!important;
	}
}
.header{
	width: 100%;
	height: 0.9rem;
	font-size: 0.36rem;
	line-height: 0.9rem;
	display: flex;
	justify-content: space-between;
	box-shadow: 0 0.01rem 0.02rem #aaa;
	position: fixed;
	top: 0;
	z-index: 9999;
	background:#fff;
	a{
		color: #000;
		margin-left: 0.5rem;
		i{
			display: inline-block;
		}
	}
	span{
		width: 60%;
		float: right;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	img{
		width: 35px;
		height: 35px;
		margin-top: 5px;
		margin-right: 5%;
	}
}
.position{
	width: 100%;
	height: 0.9rem;
	z-index: 9;
}
#sign-btn{
		width: 100%;
		height: 5vh;
		background: #409eff;
		color: #fff;
		font-size: 18px;
		font-weight: 700;
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		bottom: 0;
		left: 0;
		letter-spacing: 2px;
	}
.tips{
	margin: 0.3rem;
	height: 0.6rem;
	line-height: 0.6rem;
	width: 3rem;
	color: #fff;
	background: #42b574;
	display: block;
	margin-bottom: 2vh;
}
.title{
	width: 96%;
	margin: 0 auto;
	height: 50px;
	border-bottom: 1px solid #ccc;
	text-align: left;
	line-height: 45px;
	font-weight: 700;
	font-size: 18px;
	position: sticky;
	top:45px;
	background: #F6F6F6;
	left: 0;
	.matchName,img{
		vertical-align: top;
	}
	.matchName{
		display: inline-block;
		white-space: nowrap;
		width: 85%;
		overflow: hidden;
		text-overflow: ellipsis;
		padding-left: 2%;
	}
	img{
		width: 30px;
		height: 30px;
		object-fit: cover;
		position: absolute;
		top: 50%;
		right: 0;
		transform: translateY(-50%);
	}
}

.teamBtnParen {
  display: flex;
  justify-content: space-between;

  .judgmentApply {
    width: 1.6rem;
    height: 0.6rem;
    border: 1px #bbbbbb solid;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 0.2rem;
    margin-right: 0.2rem;
  }
}

.logo {
  display: inline-block;
  width: 0.6rem;
  height: 0.6rem;
}

.apply {
  .matchInfo {
    padding: 0.2rem 0.3rem;

    .matchName {
      height: 0.8rem;
      line-height: 0.8rem;
      font-weight: bold;
      font-size: 0.34rem;
      padding-left: 0.15rem;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .matchInfo {
      padding: 0.2rem;
      display: flex;
      flex-direction: column;
      text-align: left;
      justify-content: space-around;
      // height: 4rem;
      font-size: 0.28rem;
      border-bottom: 0.02rem solid #bbbbbb;
      div{
        line-height: 6.4vw;
      }
    }
    .teamBtn {
      margin-top: 0.2rem;
      height: 0.6rem;
      line-height: 0.6rem;
      width: 3rem;
      color: #fff;
      background: #42b574;
    }

    .teamList {
      .teamItem {
        font-weight: bold;
        padding: 0.2rem;
        // height: 2rem;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        margin: 0.2rem 0;
        border-bottom: 0.02rem dashed #bbbbbb;

        .teamItem-top {
          text-align: left;
        }

        .teamItem-middle {
          display: flex;
          justify-content: space-between;
        }

        .teamItem-bot {
          display: flex;
          justify-content: space-between;

          .signBtn {
            width: 1.4rem;
            height: 0.4rem;
            line-height: 0.4rem;
            background: #fff;
            color: #42b574;
            border: 0.02rem solid #42b574;
          }

          .signBtn:hover {
            transition: 0.5s;
            background: #c0e6d1;
          }
        }
      }

      .teamItem:first-child {
        /*border-top: 0.02rem dashed #bbbbbb;*/
      }
    }
  }
	
}
</style>
